package work.thread_eg.concurrent.synchronized_eg;

/**
 * @author shenminglong@kedacom.com
 * @date 2022-01-11
 */
public class SyncThread implements Runnable {
    // static的变量在内存中只有一份的
    // 多个SyncThread的对象是共享一个count变量
    // 所以每个线程都new的新的 SyncThread对象 count的值也是只有一份 共享的
    private static int count;
    public SyncThread() {
        count = 0;
    }

    public void run() {
        synchronized (this){
            for (int i = 0; i < 5; i++) {
                try {
                    System.out.println("线程名:"+Thread.currentThread().getName() + ":" + (count++));
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public synchronized static void method() {
        for (int i = 0; i < 5; i++) {
            try {
                System.out.println("线程名:"+Thread.currentThread().getName() + ":" + (count++));
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public int getCount() {
        return count;
    }
}